package com.shuai.chatroom.service;

import com.shuai.chatroom.entity.FriendInfo;
import com.shuai.chatroom.entity.MessageInfo;
import com.shuai.chatroom.entity.SessionsInfo;
import com.shuai.chatroom.entity.vo.FriendInfoVO;
import com.shuai.chatroom.entity.vo.SessionInfoVO;
import com.shuai.chatroom.mapper.SessionsMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class SessionsService {
    @Resource
    private SessionsMapper sessionsMapper;

    @Resource
    private MessageService messageService;

    public List<SessionInfoVO> getSessionInfoVOS(Integer uId) {
        List<Integer> sessionIds = sessionsMapper.getSessionIds(uId);
        ArrayList<SessionInfoVO> sessionInfoVOS = new ArrayList<>();
        for (Integer sessionId : sessionIds) {
            SessionInfoVO sessionInfoVO = new SessionInfoVO();
            sessionInfoVO.setSessionId(sessionId);
            sessionInfoVO.setFriendInfoVOS(sessionsMapper.getFriendsBySessionId(sessionId, uId));
            //设置会话的访问时间
            sessionInfoVO.setUpdateTime(getUpdateTime(sessionId));
            sessionInfoVOS.add(sessionInfoVO);
            MessageInfo lastMessageInfo = messageService.getLastMessageInfo(sessionId);
            if (lastMessageInfo != null) {
                String lastMessage = lastMessageInfo.getMessContent();
                if (lastMessage.length() > 9) {
                    lastMessage = lastMessage.substring(0, 8) + "...";
                }
                sessionInfoVO.setLastMessage(lastMessage);
            } else {
                sessionInfoVO.setLastMessage("");
            }
            //插入未读消息的条数
            sessionInfoVO.setDidNotNum(messageService.getNoReadMessNum(sessionId,uId));
        }
        return sessionInfoVOS;
    }

    public SessionsInfo addSession(Integer uId, Integer toUId) {
        SessionsInfo sessionsInfo = new SessionsInfo();
        sessionsMapper.addSession(sessionsInfo);    //主键回显
        //TODO: 新增会话后还没有返回更新时间
        sessionsMapper.addSessionUser(sessionsInfo.getSessionId(), uId, toUId);
        return sessionsInfo;
    }

    public List<FriendInfoVO> getFriendsList(Integer sessionId, Integer uId) {
        return sessionsMapper.getFriendsBySessionId(sessionId, uId);
    }


    public LocalDateTime getUpdateTime(Integer sessionId) {
        return sessionsMapper.getUpdateTime(sessionId);
    }

    /**
     * 更新会话时间
     */
    public int updateTime(Integer sessionId) {
        return sessionsMapper.updateSessionTime(sessionId);
    }
}
